const express=require('express')
const CryptoJs=require('crypto-js')
const AdminModel=require('../models/admin')
const {getToken}=require('../utils/token')

const router=express.Router()
//用户登录
router.post('/',(req, res, next)=>{
    const {username,password}=req.body
    AdminModel.find({username}).then(data=>{
        if(data.length>0){
            const userInfo={
                ...data[0]._doc
            }
            //存在用户，则比较密码是否匹配
            if(CryptoJs.MD5(password).toString()!==userInfo.password){
                //密码不匹配
                res.json({
                    code:200,
                    data:{
                        status:400,
                        message:"用户名或者密码错误！",
                        userInfo:null
                    }
                })
                return
            }
            //密码匹配
            delete userInfo.password
            const token=getToken({
                _id:userInfo._id,
                username:userInfo.username
            })
            res.json({
                code:200,
                data:{
                    status:200,
                    message:"登录验证成功！",
                    userInfo:{
                        ...userInfo,
                        token
                    }
                }
            })
            return
        }
        //不存在该用户
        res.json({
            code:200,
            data:{
                status:400,
                message:"用户名或者密码错误！"
            }
        })
    })
})

module.exports=router